package com.dianrui.agent.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dianrui.agent.R;
import com.dianrui.agent.adapter.OrderListAdapter;
import com.dianrui.agent.bean.OrderList;
import com.dianrui.agent.okhttp.OkHttpRequest;
import com.dianrui.agent.util.SharedUtil;
import com.dianrui.agent.util.StringUtils;
import com.dianrui.agent.util.ToastUtil;
import com.dianrui.agent.util.Url;
import com.google.gson.JsonObject;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SearchOrderActivity extends BaseActivity {
    private int pageIndex=1;
    private List<OrderList> orderListAll = new ArrayList<>();
    private OrderListAdapter orderListAdapter;
    private String status;


    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.search_edit_content)
    EditText searchEditContent;

    @Override
    public int getContentViewId() {
        return R.layout.activity_search;
    }

    @Override
    public void initView() {
        searchEditContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                getCarOrder(true);

            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(SearchOrderActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        orderListAdapter = new OrderListAdapter(R.layout.item_order_list, orderListAll, SearchOrderActivity.this);
        recyclerView.setAdapter(orderListAdapter);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getCarOrder(true);
                refreshLayout.finishRefresh();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageIndex++;
                getCarOrder(false);
                refreshLayout.finishLoadMore();
            }
        });

        orderListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                OrderList orderList = (OrderList) adapter.getItem(position);
                Intent intent = new Intent(SearchOrderActivity.this, TrackPathActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("orderid", orderList.order_id);
                bundle.putString("starttime", orderList.start_time);
                bundle.putString("endtime", orderList.end_time);
                bundle.putInt("tagFrom",TrackPathActivity.TAG_FROM_PROGRESS);
                intent.putExtras(bundle);
                startActivityForResult(intent,999);
            }
        });

    }


    private void getCarOrder(final boolean isRfresh) {
        if (isRfresh) {
            pageIndex=1;
        }
        JsonObject orderListJson =new JsonObject();
        orderListJson.addProperty("keywords",searchEditContent.getText().toString());
        orderListJson.addProperty("p",pageIndex);
        OkHttpRequest.getInstance().postTokenRequests(SharedUtil.getUrl()+Url.ORDER_LIST, orderListJson.toString(),  new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (isRfresh) {
                    orderListAll.clear();
                }
                if (!StringUtils.isEmpty(result)&&!isFinishing()) {
                    try {
                        JSONObject jsonObject=new JSONObject(result);
                        if ("1000".equals(jsonObject.optString("status"))) {
                            JSONArray orderLists = jsonObject.optJSONObject("data").optJSONArray("order_list");
                            if (orderLists.length()>0) {
                                for (int i = 0; i <orderLists.length() ; i++) {
                                    OrderList orderList=new OrderList();
                                    orderList.order_id = orderLists.optJSONObject(i).optString("order_id");
                                    orderList.start_time = orderLists.optJSONObject(i).optString("start_time");
                                    orderList.end_time = orderLists.optJSONObject(i).optString("end_time");
                                    orderList.mobile = orderLists.optJSONObject(i).optString("mobile");
                                    orderList.account = orderLists.optJSONObject(i).optString("account");
                                    orderList.number = orderLists.optJSONObject(i).optString("number");
                                    orderList.duration_time = orderLists.optJSONObject(i).optString("duration_time");
                                    orderList.status = orderLists.optJSONObject(i).optString("status");
                                    orderList.money = orderLists.optJSONObject(i).optString("money");
                                    orderListAll.add(orderList);
                                }
                                orderListAdapter.setNewData(orderListAll);
                                refreshLayout.finishRefresh();
                            }else {
                                refreshLayout.finishRefresh();
                            }
                        }else if ("1001".equals(jsonObject.optString("status"))) {
                            ToastUtil.showToast(jsonObject.optString("message"));
                        }else if ("1002".equals(jsonObject.optString("status"))) {
                            spUtils.clear();
                            ToastUtil.showToast(jsonObject.optString("message"));
                            JumpActivitys(LoginActivity.class);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (orderListAll.size() <= 0) {
                    orderListAdapter.setEmptyView(LayoutInflater.from(SearchOrderActivity.this).inflate(R.layout.empty_view, null));
                    //recyclerView.setVisibility(View.GONE);
                } else {
                    recyclerView.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void FailedRequest(String result) {
                refreshLayout.finishLoadMoreWithNoMoreData();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }
    @OnClick(R.id.cancel_search)
    public void onViewClicked() {
        finish();
    }
}
